﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BSC_OTC_Management.Forms
{
    public partial class Frm_GanNDD_HDDL : Form
    {
        #region Khai bao bien
        Code.CL_Ultility _cl = new Code.CL_Ultility();
        Code.StaticVariable _code = new Code.StaticVariable();
        List<String> listNDD = new List<string>();
        DataTable _tableControl = new DataTable();
        DataTable _tableValue = new DataTable("tableValue");
        DataTable oldTableValue = new DataTable("oldTableValue");
        private string _function;
        private string _formName;
        string _ID = "";
        string _ID_ColumnName = "";
        string _formTitle = "";
        #endregion

        public Frm_GanNDD_HDDL()
        {
            InitializeComponent();
        }

        public Frm_GanNDD_HDDL(string formName, string formTitle, string function, string _ID, string _ID_ColumnName)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            this.gbTT.Enabled = true;
            btnFunction.Visible = true;
            this._function = function;
            this._formName = formName;
            this._formTitle = formTitle;
            this._tableControl = _code._services.GetFldMasterBy_Objname(_formName);
            if (_ID != "")
            {
                this._ID = _ID;
            }
            if (_ID_ColumnName != "")
            {
                this._ID_ColumnName = _ID_ColumnName;
            }

            //đ? d? li?u cho combobox vai tr?
            //cbbVaitro();
            //ki?m tra xem đây là fuction nào?
            switch (this._function)
            {
                case "AddNew":
                    btnFunction.Text = "Thêm mới";
                    break;
                case "Edit":
                    btnFunction.Text = "Sửa";
                    ShowData();
                    break;
                case "View":
                    this.gbTT.Enabled = false;
                    btnFunction.Visible = false;
                    ShowData();
                    break;
                default:
                    break;

            }
        }

        private void cbbVaitro (){
            
            try
            {
                String sql = "SELECT CDVAL VALUECD, CDVAL VALUE, CDCONTENT DISPLAY FROM ALLCODE WHERE CDTYPE = 'BSC_TBL_NDDTCPH' AND CDNAME = 'VAITRO' and cduser='Y' ORDER BY lstodr";
            
                DataTable table = new DataTable("vaitro");
                table = _cl._services.GetDatatable_BySQL(sql);

                if (table.Rows.Count > 0)
                {
                    Dictionary<string, string> obj = new Dictionary<string, string>();
                    foreach (DataRow row in table.Rows)
                    {
                        obj.Add(row["VALUE"].ToString(), row["DISPLAY"].ToString());
                    }
                    this.cbb_vaitro.DataSource = new BindingSource(obj, null);
                    this.cbb_vaitro.DisplayMember = "Value";
                    this.cbb_vaitro.ValueMember = "Key";
                    this.cbb_vaitro.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,Code.StaticVariable.messeseboxLuuY);
            }
        }

        private void ShowData(){
            // l?y d? li?u theo ID
             //oldTableValue = _code._services.GetDatatable_BySQL("select * from " + this._formName + " where " + this._ID_ColumnName + " like '" + this._ID + "'");
             oldTableValue = _code._services.SearchView_BySQL(this._formName, " and " +this._ID_ColumnName + " like '" + this._ID + "'");
            
            if (oldTableValue.Rows.Count > 0)
            {
                txt_sohd.Text = oldTableValue.Rows[0]["tenhd"].ToString();
                txt_sohd.Name = oldTableValue.Rows[0]["sohd"].ToString();
                txt_tcph.Text = oldTableValue.Rows[0]["TEN"].ToString();
                txt_tcph.Name = oldTableValue.Rows[0]["TCPHID"].ToString();
                SetNDDToCombobox(txt_tcph.Name);

                for (int i = 0; i < listNDD.Count; i ++){
                    if (listNDD[i] == oldTableValue.Rows[0]["mandd"].ToString())
                        cbb_ndd.SelectedIndex = i;
                }
                txt_vaitro.Text = oldTableValue.Rows[0]["vaitro"].ToString();
                /*for (int i = 0; i < cbb_vaitro.Items.Count; i++)
                {
                    string vaitro = ((KeyValuePair<string, string>)cbb_vaitro.Items[i]).Key;
                    if (vaitro == oldTableValue.Rows[0]["vaitro"].ToString())
                        cbb_vaitro.SelectedIndex = i;
                }*/
                //cbb_ndd.SelectedText = oldTableValue.Rows[0]["sohd"].ToString();
            }

        }

        private void txt_sohd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                try
                {
                    //chuy?n sang Form View đ? t?m ki?m S? trái ch?
                    Forms.FrmView _FrmView = new Forms.FrmView("BSC_TBL_HOPDONGDAILY", "Thông tin Hợp đồng đại lý", true);
                    _FrmView.ShowDialog();
                    //l?y v? d? li?u DataTable formView Sotraichu
                    DataTable dt = Code.StaticVariable._tbl;
                    String sohd = "", tenhd = "", tcphid = "", tentcph = "";
                    if (dt.Columns.Count >= 5 && dt.Rows.Count >= 1)
                    {
                        sohd = dt.Rows[0]["sohd"].ToString();
                        tenhd = dt.Rows[0]["tenhd"].ToString();
                        tcphid = dt.Rows[0]["tcphid"].ToString();
                        tentcph = dt.Rows[0]["ten"].ToString();
                        txt_sohd.Text = tenhd; //hthọ tên Hd
                        txt_sohd.Name = sohd; //giá trị là sohd
                        txt_tcph.Text = tentcph;
                        txt_tcph.Name = tcphid;
                    }
                    Code.StaticVariable._tbl.Clear();
                    SetNDDToCombobox(tcphid);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                this.Close();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void SetNDDToCombobox (string _tcphid){

            DataTable _tbl = new DataTable("tbl");
            String sql = "Select ndd.mandd, ndd.tenndd from bsc_tbl_nguoidaidien ndd where ndd.tcphid = '"+ _tcphid +"'";
            _tbl = _cl._services.GetDatatable_BySQL(sql);
            if (_tbl.Rows.Count >= 1)
            {
                listNDD.Clear();
                cbb_ndd.Items.Clear();
                for(int i = 0; i < _tbl.Rows.Count; i++)
                {
                    listNDD.Add(_tbl.Rows[i]["mandd"].ToString());
                    cbb_ndd.Items.Add(_tbl.Rows[i]["mandd"].ToString() + "-" + _tbl.Rows[i]["tenndd"].ToString());
                }
            }

        }

        private void btnFunction_Click(object sender, EventArgs e)
        {
            foreach (DataRow _row in this._tableControl.Rows)
            {
                this._tableValue.Columns.Add(_row["fldname"].ToString());
            }
            //add parameter duyet
            //_tableValue.Columns.Add("DUYET");

            if (!Check_Null())
                return;
            int selectedNDD = cbb_ndd.SelectedIndex;
            _tableValue.Rows.Add(listNDD[selectedNDD], txt_tcph.Name, txt_sohd.Name, txt_vaitro.Text);//((KeyValuePair<string, string>)cbb_vaitro.SelectedItem).Key

            // T?o xong row chưa d? li?u, t?o thêm 1 row ch?a ki?u d? li?u
            DataRow rowDataType = _tableValue.NewRow();
            int stt = 0;
            foreach (DataRow _row in this._tableControl.Rows)
            {
                rowDataType[stt] = _row["fldtype"].ToString();
                stt++;
            }
            //add data of duyet
            //rowDataType["DUYET"] = "T";
            this._tableValue.Rows.Add(rowDataType);
            //string message box
            string msg = "";

            switch (this._function)
            {
                case "AddNew":
                        msg = _code._services.AddNewRow_ReturnID(this._formName, this._tableValue);
                        try
                        {
                            int id = Convert.ToInt32(msg);
                            //lưu vết giao dịch
                            _code._services.WritetoTLLOG(Code.StaticVariable.userID,
                                                            "",
                                                            Code.StaticVariable.menu_Code,
                                                            _cl.Current_DATE("dd/MM/yyyy"),
                                                            "",
                                                            _cl.Current_DATE("hh:mm:ss"),
                                                            "",
                                                            (int)Code.StaticVariable.approveCase.ChuaDuyet + "",
                                                            this._function,
                                                            msg,
                                                            DataTableToString(_tableValue));
                            //luu vet nguoi thuc hien
                            _code._services.Update_Last_Change(_formName, msg, Code.StaticVariable.userID);
                             MessageBox.Show(Code.StaticVariable.messeseboxThemmoiThanhCong, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                             this.Close();
                        }
                        catch (Exception ex)
                        {
                            this._tableValue = new DataTable("noname");
                            MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                        }
                  
                    break;
                case "Edit":
                    try
                    {
                        //so sanh du lieu giua 2 bang xem co sua ko?
                        if (!Compare2Table(oldTableValue, _tableValue)) //có sửa dl
                        {
                            msg = _code._services.WriteToMaintain_log(this._formName, this._tableValue, oldTableValue, this._ID_ColumnName, this._ID, Code.StaticVariable.userID);
                            bool b = _code._services.Approve_Data(this._formName, this._ID_ColumnName, this._ID, (int)Code.StaticVariable.approveCase.ChuaDuyet);
                            _code._services.WritetoTLLOG(Code.StaticVariable.userID,
                                                           "",
                                                           Code.StaticVariable.menu_Code,
                                                           _cl.Current_DATE("dd/MM/yyyy"),
                                                           "",
                                                           _cl.Current_DATE("hh:mm:ss"),
                                                           "",
                                                           (int)Code.StaticVariable.approveCase.ChuaDuyet + "",
                                                           this._function,
                                                           this._ID,
                                                           DataTableToString(_tableValue));
                            //luu vet nguoi thuc hien
                            _code._services.Update_Last_Change(_formName, this._ID, Code.StaticVariable.userID);
                            MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                            this.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        this._tableValue = new DataTable("noname");
                        MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OK);
                    }

                    break;
                default:
                    break;
            }
            this.Close();
        }

        private bool Check_Null()
        {
            if (txt_tcph.Text.Length == 0 || txt_sohd.Text.Length == 0 || cbb_ndd.Text.Length == 0 ){
                MessageBox.Show("Không được để trống dữ liệu!");
                return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public string DataTableToString(DataTable dt)
        {
            string _str = "";
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                    _str += dt.Rows[0][i].ToString() + ".";

                _str = _str.Substring(0, _str.Length - 1);
            }

            return _str;
        }

        public bool Compare2Table(DataTable _oldTable, DataTable _newTable)
        {
            if (_oldTable.Rows.Count > 0 && _newTable.Rows.Count > 0)
            {
                foreach (DataColumn col in _newTable.Columns)
                {

                    string _old = _oldTable.Rows[0][col.ColumnName].ToString();
                    string _new = _newTable.Rows[0][col.ColumnName].ToString();
                    if (_old != _new)
                        return false;
                }
            }
            else
                return false;
            return true;
        }

    }
}
